const tokens = require('../../services/tokenService');
// const user = require('../../model/userModel/userModel');
const { userModel, orgInfoModel } = require('../../model');
const { getResultToObjectComplete } = require('../../services/utils');

module.exports = {
  login: async (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.send({
        code: 60204,
        message: '账号或密码不能为空'
      })
    }

    const attributes = [
      'org',
      'account',
      'roles',
      'avatar',
      'name'
    ];

    // TODO 用户密码加密
    const where = {
      account: username,
      password: password
    };

    const member = await userModel.findOne(attributes, where);
    if (member) {
      const { org, account, roles, avatar, name } = member;
      const token = tokens.createToken({
        org: org,
        account: account,
        roles: [roles],
        avatar: avatar,
        name: name
      },3600 * 24 * 7);
      return res.send({
        code: 20000,
        data: {
          token: token
        }
      })
    } else {
      return res.send({
        code: 60204,
        message: '账号或密码错误'
      })
    }
  },
  info: function (req, res) {
    const { token } = req.query;
    tokens.checkToken(token, async (err,decode) => {
      if (err) return res.send({code: 50008, message: '用户身份失效 请重新登录'});

      const org_info = await orgInfoModel.findOne(['icon', 'name'], { id: decode.org});

      return res.send({
        code: 20000,
        data: {
          ...decode,
          icon: org_info.icon,
          org_name: org_info.name
        }
      });
    })
  },
  logout: function (req, res) {
    return res.send({
      code: 20000,
      data: 'success'
    })
  }
};
